<?php

namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\goods\LihuaStock;
use app\common\model\LihuaOrder;
use app\common\model\LihuaRefund; //退单记录
use app\common\model\LihuaOrderGoods;
use app\common\model\LihuaUserbonus;
use app\common\model\LihuaHongbao;
use app\common\model\LihuaActivity; //城市活动表
use app\common\model\LihuaOrderActivity; //订单活动表
use app\common\model\User;
use fast\Http;
use think\Db;
use think\Exception;
use think\Validate;
use think\Log;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1', 'ip_city'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({ 'code':'1', 'msg':'返回成功' }) 
     */
    public function test()
    {
        $price = '12.65'; //消费金额
        $user_price = bcsub($price, '2.5', 2); //使用本金部分
        $this->success('返回成功', [$price, $user_price]);
    }

    public function ip_city()
    {
        /**
         * 首先查询出对应的用户
         * 计算出上周的时间
         * **/
        $s1 = $this->request->request('s1', ''); //起始日期
        $s2 = $this->request->request('s2', ''); //截止日期
        if (!$s1 || !$s2) $this->error('参数错误');
        $time_s = strtotime($s1." 00:00:00");
        $time_e = strtotime($s2." 23:59:59");
        $list = User::where('jointime' , 'BETWEEN', [$time_s, $time_e])->select();
        $list = collection($list)->toArray();
        $joinip_arr = array_column($list, 'joinip');
        $res_arr_bj = []; //北京
        $res_arr_sh = []; //上海
        $res_arr_cz = []; //常州
        $res_arr_sz = []; //苏州
        $res_arr_wx = []; //无锡
        $res_arr_nj = []; //南京
        $res_arr_gz = []; //广州
        $res_arr_other = []; //其他

        foreach ($list as $k => $v) {
            $ip = $v['joinip'];
            $csmip = \addons\csmip\library\Csmip::getInstance();
            $region = $csmip->getRegion($ip);
            if($region->city=='北京市') $res_arr_bj[] = ['city'=> $region->city, 'ip'=> $ip];
            if($region->city=='上海市') $res_arr_sh[] = ['city'=> $region->city, 'ip'=> $ip];
            if($region->city=='无锡市') $res_arr_wx[] = ['city'=> $region->city, 'ip'=> $ip];
            if($region->city=='常州市') $res_arr_cz[] = ['city'=> $region->city, 'ip'=> $ip];
            if($region->city=='苏州市') $res_arr_sz[] = ['city'=> $region->city, 'ip'=> $ip];
            if($region->city=='南京市') $res_arr_nj[] = ['city'=> $region->city, 'ip'=> $ip];
            if($region->city=='广州市') $res_arr_gz[] = ['city'=> $region->city, 'ip'=> $ip];
            if($region->city=='其他') $res_arr_other[] = ['city'=> $region->city, 'ip'=> $ip];
        }
        echo '订餐平台各地区新增用户统计<br/>';
        echo '北京:' . count($res_arr_bj). '<br/>';
        echo '上海:' . count($res_arr_sh). '<br/>';
        echo '无锡:' . count($res_arr_wx). '<br/>';
        echo '常州:' . count($res_arr_cz). '<br/>';
        echo '苏州:' . count($res_arr_sz). '<br/>';
        echo '南京:' . count($res_arr_nj). '<br/>';
        echo '广州:' . count($res_arr_gz). '<br/>';
        echo '其他:' . count($res_arr_other). '<br/>';
        echo '<br/><br/>';
        echo '其他未识别IP展示:<br/>';
        foreach ($res_arr_other as $k => $v) {
            echo $v['ip']. '<br/>';
        }
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

    //数据迁移备份
    public function copy_data_bank()
    {
        $year = $this->request->post('year'); //拷贝年份
        $list = OrderModel::where([ 'add_time'=>['like', '%'.$year.'%'] ])->select();
        foreach ($list as $k => $v) {
            $goodlist = OrderGoods::where(['order_sn'=> $v['sn']])->select();
            $v['goodlist'] = $goodlist;
        }
        // $s = OrderModel::getLastSql();
        $this->success('OK', ['list' => $list]);
    }

    public function execute()
    {
        $cityArr = LihuaCity::getCityArr();
        foreach ($cityArr as $k => $v) {
            $this->copyData($k, $v);
        }
        $output->info(date('Y-m-d H:i:s').' 复制老系统商品数据成功');
    }

    public function copyData()
    {
        $city_id = $this->request->post('city_id'); 
        $city_name = $this->request->post('city_name'); 

        $res = Http::post('https://api.lihua.com/index/Good/copyOldGoodData',
            ['cityname' => $city_name, 'current_date' => date('Y-m-d')]);
        if ($res) {
            $arr = json_decode($res, true);
            if (!is_null($arr)) {
                if ($arr['status'] == 1) {
                    $cateList = $arr['data']['cate_list'];//分类列表
                    $goodList = $arr['data']['good_list'];//商品列表
                    $cateCnt  = count($cateList);
                    foreach ($cateList as $k => $v) {
                        $data = [
                            'old_id'  => $v['id'],
                            'city_id' => $city_id,
                            'name'    => $v['title'],
                            'weigh'   => bcsub(100, $v['sort'], 0),
                            'status'  => 1,
                        ];
                        $cateCnt--;
                        try {
                            $row = Db::name('lihua_category')->where('old_id', $v['id'])->find();
                            if ($row) {
                                Db::name('lihua_category')->where('id', $row['id'])->update($data);
                            } else {
                                Db::name('lihua_category')->insert($data);
                            }
                        } catch (\Exception $e) {
                            $this->log($e->getMessage());
                        }
                    }

                    $cates = Db::name('lihua_category')->where('city_id', $city_id)->column('old_id,id');
                    $goodList = array_reverse($goodList);
                    foreach ($goodList as $k => $v) {
                        $data = [
                            'old_id'        => $v['id'],
                            'city_id'       => $city_id,
                            'category_id'   => isset($cates[$v['category_id']]) ? $cates[$v['category_id']] : 0,
                            'name'          => $v['name'],
                            'short_name'    => $v['short'],
                            'description'   => $v['desc'],
                            'pic'           => $v['pic'],
                            'type'          => $v['is_alone_sale'] == 1 ? 1 : 2,
                            'price'         => round($v['promote_price'], 2)>0 ?  $v['promote_price'] : $v['price'], //商品价格
							'original_price'=> $v['price'],  //商品原价
                            'box_fee'       => $v['box_fee'],
                            'is_alone_sale' => $v['is_alone_sale'] == 2 ? 0 : 1,
                            'sale_start'    => $v['sale_start_date'],
                            'sale_end'      => $v['sale_end_date'],
                            'limit_num'     => $v['limit_num'],
                            'at_least'      => $v['at_least'],
                            'status'        => 1,
                        ];
                        try {
                            $row = LihuaGoods::where('old_id', $v['id'])->field('id')->find();
                            if ($row) {
                                LihuaGoods::where('id', $row['id'])->update($data);
                            } else {
                                LihuaGoods::create($data);
                            }
                        } catch (\Exception $e) {
                            $this->log($e->getMessage());
                        }
                    }
                } else {
                    $this->log($arr['message']);
                }
            } else {
                $this->log('源数据JSON: ' . json_last_error_msg());
            }
        } else {
            $this->log('未获取到' . $city_name . '今日商品数据');
        }
    }

    protected function log($msg = '')
    {
        echo date('Y-m-d H:i:s ') . $msg . "\n";
    }

}
